#!/usr/bin/python
# -*- coding: utf-8 -*-

from celery.task import Task
from celery.registry import tasks
from celery import task
import logging

#from twisted.protocols import basic
#from twisted.protocols import basic
#from twisted.internet import epollreactor
#epollreactor.install()
#from twisted.internet import reactor, protocol
#from twisted.application import service, internet

#from twisted.internet import reactor


import threading

import time


#class MyChat(basic.LineReceiver):
#        def connectionMade(self):
#            self.factory.clients.append(self)

#        def connectionLost(self, reason):
#            self.factory.clients.remove(self)

#        def dataReceived(self, line):
#                print line
#                for c in self.factory.clients:
#                    c.message(str(len(factory.clients))+'\r\n')

#        def message(self, message):
#            self.transport.write(message)



#class ServerThread():

#    def __init__(self):
#        self.amount=0

#        self.factory = protocol.ServerFactory()
#        self.factory.protocol = MyChat
#        self.factory.clients = []


#    def run(self):
#        from twisted.internet import reactor
#        try:
#            reactor.listenTCP(8001,self.factory)
#            reactor.run()
#        except Exception, e:
#            print "Couldn't do it: %s" % e
#        while self.amount<10:
#            print "thread tik (read socket)"
#            time.sleep(1)
#            self.amount+=1



class SocketServerStart(Task):

    def run(self, ip, **kwargs):
        self.logger=logging.getLogger(__name__)
        from models import Socket
        from dapi.models import Var
        w_connection_status=Var.objects.filter(name="WEB_SOCKET_PORT_STATUS")
        w_connection=Var.objects.filter(name="WEB_SOCKET_PORT")
        s_connection_status=Var.objects.filter(name="SERIAL_PORT_STATUS")
        s_connection=Var.objects.filter(name="SERIAL_PORT")
        print s_connection_status.all()[0].get_value(), type(s_connection_status)
        if s_connection_status.all()[0].value=="1":
            #self.logger.info("kill serial")
            s_port.close_connection()
        else:
            #self.logger.info("run serial")
            s_port=s_connection.all()[0].get_value()
            #self.logger.info("и серйный порт: %s" % (s_port)) 
            s_port.get_connection()
        # web socket
        if w_connection_status.all()[0].value=="1":
            #self.logger.info("kill socket")
            w_port.close_connection()
        else:
            #self.logger.info("run socket")
            w_port=w_connection.all()[0].get_value()
            #self.logger.info("Пытаемся открыть web socket: %s" % (w_port)) 
            w_port.get_connection()
        





        return w_port.getSocket(),s_port.getSocket()
